package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: qingtao
 * @Date 2022/3/14 14:32
 */
@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private SetmealDishMapper setmealDishMapper;

    /**
     * 查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    @Cacheable(value = "setmealCache",key = "'setmeal'")
    public Page<SetmealDto> findByPage(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page, pageSize);
        List<Setmeal> setmealList = setmealMapper.findAllByName(name);
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealList);
        //将setmeal数据复制到setmealDto
        List<SetmealDto> setmealDtos = setmealList.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);
            Category category = categoryMapper.findAllById(setmealDto.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());
        Page<SetmealDto> page1 = new Page<>();
        page1.setRecords(setmealDtos);
        page1.setTotal(pageInfo.getTotal());
        page1.setPage(pageInfo.getPageNum());
        page1.setPageSize(pageInfo.getPageSize());
        return page1;
    }

    /**
     * 添加
     *
     * @param setmealDto
     * @return
     */
    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public boolean save(SetmealDto setmealDto, Long employeeId) {
        Setmeal setmealName = setmealMapper.findByName(setmealDto.getName());
        if (setmealName != null && setmealName.getIsDeleted() == 0) {
            throw new BusinessException("添加的名字重复请重新输入");
        } else if (setmealName != null && setmealName.getIsDeleted() != 0) {
            throw new BusinessException("添加的数据需要恢复");
        }
        setmealDto.setStatus(1);
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setCreateUser(employeeId);
        setmealDto.setUpdateUser(employeeId);
        setmealMapper.save(setmealDto);

        List<SetmealDish> collect = setmealDto.getSetmealDishes().stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setCreateTime(LocalDateTime.now());
            setmealDish.setUpdateTime(LocalDateTime.now());
            setmealDish.setUpdateUser(employeeId);
            setmealDish.setCreateUser(employeeId);
            setmealDish.setSort(0);
            return setmealDish;
        }).collect(Collectors.toList());
        setmealDishMapper.save(collect);
        return true;
    }


    /**
     * 删除
     *
     * @param ids
     * @param id
     * @return
     */
    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public boolean delete(List<Long> ids, Long id) {
        Integer status = setmealMapper.findByStatus(ids);
        if (status > 0) {
            throw new BusinessException("起售的套餐不能删除，请先修改状态");
        }
        setmealMapper.delete(ids, id, LocalDateTime.now());
        setmealDishMapper.delete(ids, id, LocalDateTime.now());
        return true;
    }

    /**
     * 修改状态
     *
     * @param ids
     * @param status
     * @param updateUser
     * @return
     */
    @Override
    @CacheEvict(value = "setmealCache",allEntries = true)
    public boolean updateStatus(List<Long> ids, Integer status, Long updateUser) {
        setmealMapper.updateStatus(ids, status, updateUser, LocalDateTime.now());
        return true;
    }

    /**
     * 修改
     *
     * @param setmealDto
     * @return
     */
    @Override
    @CacheEvict(value = "setmealCache",allEntries = true)
    public boolean update(SetmealDto setmealDto, Long updateUser) {
        Setmeal sMName = setmealMapper.findByName(setmealDto.getName());
        if (sMName != null && !setmealDto.getId().equals(sMName.getId())) {
            throw new BusinessException("修改后的名字在数据库已经存在");
        }

        //判断是否是删除状态
        if (sMName != null && sMName.getIsDeleted() == 1) {
            throw new BusinessException("修改后的菜品需要恢复");
        }

        //修改sermeal
        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setUpdateUser(updateUser);
        setmealMapper.update(setmealDto);
        //先删除套餐的关联菜品
        setmealDishMapper.deleteByDishId(setmealDto.getId());
        List<SetmealDish> collect = setmealDto.getSetmealDishes().stream().map(setmealDish -> {
            setmealDish.setSort(0);
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setUpdateTime(LocalDateTime.now());
            setmealDish.setUpdateUser(updateUser);
            setmealDish.setCreateTime(setmealDto.getCreateTime());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            return setmealDish;
        }).collect(Collectors.toList());
        setmealDishMapper.save(collect);
        return true;
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public SetmealDto findById(Long id) {
        Setmeal setmeal = setmealMapper.findById(id);
        List<SetmealDish> setmealDishes = setmealDishMapper.findBySetmealId(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(setmealDishes);
        return setmealDto;
    }

    /**
     * 根据套餐的类别展示套餐
     *
     * @param categoryId
     * @param status
     * @return
     */
    @Override
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    public List<Setmeal> list(Long categoryId, Integer status) {
        return setmealMapper.list(categoryId,status);
    }

    @Override
    public List<SetmealDish> findSetmealDish(Long setmealId) {
        return setmealDishMapper.findBySetmealId(setmealId);
    }
}
